package com.example.wanxiang.service.Impl;


import com.example.wanxiang.dto.JwtRequest;
import com.example.wanxiang.dto.JwtResponse;
import com.example.wanxiang.dto.RegisterRequest;
import com.example.wanxiang.entity.User;
import com.example.wanxiang.repository.UserRepository;
import com.example.wanxiang.security.JwtService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;


@Service
@RequiredArgsConstructor
public class AuthService {

    private final UserRepository userRepository;
    private final JwtService jwtService;
    private final AuthenticationManager authenticationManager;
    private final PasswordEncoder passwordEncoder;

    public JwtResponse register(RegisterRequest request) {

        if(userRepository.findByEmail(request.getEmail())!=null)
            throw new IllegalStateException("Customer is has been registered");

        User customer = new User();
        customer.setUsername(request.getUsername());
        customer.setPassword(passwordEncoder.encode(request.getPassword()));
        customer.setEmail(request.getEmail());
        customer.setRegisterTime(LocalDateTime.now());
        customer.setRole("ROLE_USER");
        User save = userRepository.save(customer);
        if (save != null) {
            JwtResponse authResponse = getAuthResponse(customer);
            return authResponse;
        }
        else return null;
    }


    public JwtResponse authenticate(JwtRequest request) {
        Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(request.getEmail(), request.getPassword()));
        if (authenticate.isAuthenticated()) {
            User user = this.userRepository.findByEmail(request.getEmail());
            if (user == null) {
                throw new UsernameNotFoundException("Username " + request.getEmail() + "not found");
            }
            return getAuthResponse(user);
        }
        else return null ;
    }

    private JwtResponse getAuthResponse(User user) {
        JwtResponse response = new JwtResponse(jwtService.generateToken(user));
        return response;
    }

}